



//----------------------------------------
// mouse listener
function onMouseDown(event) {
    this.mouseDown = true;
    this.canvas.addEventListener('mousemove', this.onMouseMove, false);
    this.canvas.addEventListener('mouseup', this.onMouseUp, false);

    let [x, y] = this.getMousePos(event);
    this.startx = x;
    this.starty = y;
    this.lastx = x;
    this.lasty = y;
    this.scene.onMouseDown(x,y);
}

function onMouseMove(event) {
    let camera = this.camera;
    let [curX, curY] = this.getMousePos(event);
    let dx = curX - this.lastx;
    let dy = curY - this.lasty;
    this.lastx = curX;
    this.lasty = curY;
    // console.log(`dx:${dx},dy:${dy}`);
    if (Math.abs(dx) > Math.abs(dy)) {
        // 水平滑动
        camera.slide_left_to_right(-dx * 0.2);
    } else {
        camera.slide_down_to_up(-dy * 0.2);
    }

    // TODO: 是否需要注册  mouseMove???
}


function onMouseUp(event) {
    this.mouseDown = false;
    this.canvas.removeEventListener('mousemove', this.onMouseMove);
    this.canvas.removeEventListener('mouseup', this.onMouseUp);

    let [curX, curY] = this.getMousePos(event);
    this.scene.onMouseUp(curX,curY);
}

/**
 * 按下mouse (激活onMouseDown),
 * 然后将鼠标移动(激活onMouseMove)到canvas外面,
 * 最后松开 mouse, 不会激活 onMouseUp.
 * 我们让其激活  onMouseCancel
 * @param event
 */
function onMouseCancel(event) {
    console.log('onMouseCancel called!');
    this.onMouseUp(event);
}

function onMouseLeave(event) {
    if (this.mouseDown) {
        this.onMouseCancel(event);
    }
}


class InputMgr {

    constructor(scene) {
        this.scene = scene;
        this.canvas = scene.app.canvas;
        this.camera = scene.camera;

        //  按键直接注册到 scene上
        this.onKeyDown = scene.onKeyDown.bind(scene);
        this.onKeyUp = scene.onKeyUp.bind(scene);

        // mouse事件 封装一层
        this.onMouseDown = onMouseDown.bind(this);
        this.onMouseLeave = onMouseLeave.bind(this);

        this.onMouseMove = onMouseMove.bind(this);
        this.onMouseUp = onMouseUp.bind(this);
        this.onMouseCancel = onMouseCancel.bind(this);

        // 注册事件
        // 添加按键事件
        document.addEventListener('keydown', this.onKeyDown, false);
        document.addEventListener('keyup', this.onKeyUp, false);

        // 添加mouse事件
        this.canvas.addEventListener('mousedown', this.onMouseDown, false);
        this.canvas.addEventListener('mouseleave', this.onMouseLeave, false);

        //-----------------------------
        // external vars
        //
        this.mouseDown = false;
        this.startx = -1;
        this.starty = -1;
        this.lastx = -1;
        this.lasty = -1;
    }

    getMousePos(event) {
        let canvas = this.canvas;
        let rect = canvas.getBoundingClientRect();

        //获取鼠标在canvas上的位置
        let x = event.pageX - rect.left;
        let y = event.pageY - rect.top;
        return [x, y];
    }
}

module.exports = InputMgr;
